package org.luxor.commons.zookeeper.client;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.luxor.commons.zookeeper.component.WatcherManager;
import org.luxor.commons.zookeeper.exception.ZookeeperException;

/**
 * Zookeeper Watcher Client
 *
 * @author Mr.Yan  @date: 2020/12/23
 */
public class ZookeeperWatcherClient extends AbstractZookeeperClient {

    private WatcherManager watcherManager;

    public ZookeeperWatcherClient(CuratorFramework curatorFramework,WatcherManager watcherManager) {
        super(curatorFramework);
        this.watcherManager = watcherManager;
    }
    
    /**
     * 注册 节点变更监听器
     *
     * @param path              监听节点
     * @param nodeCacheListener 监听接收器
     */
    public void registerNodeWatcher(String path, NodeCacheListener nodeCacheListener) throws ZookeeperException {
        try {
            watcherManager.addNodeWatcher(path, nodeCacheListener);
        } catch (Exception e) {
            throw new ZookeeperException("注册NodeWatcher监听器失败.", e);
        }
    }

    /**
     * 移除 节点变更监听器
     *
     * @param path 监听节点
     */
    public void removeNodeWatcher(String path) throws ZookeeperException {
        try {
            watcherManager.removeNodeWatcher(path);
        } catch (Exception e) {
            throw new ZookeeperException("移除NodeWatcher监听器失败.", e);
        }
    }

    /**
     * 注册 子节点变更监听器
     *
     * @param path                      监听节点
     * @param pathChildrenCacheListener 监听接收器
     */
    public void registerPathChildrenWatcher(String path, PathChildrenCacheListener pathChildrenCacheListener) throws ZookeeperException {
        try {
            watcherManager.addPathChildrenWatcher(path, pathChildrenCacheListener);
        } catch (Exception e) {
            throw new ZookeeperException("注册PathChildrenWatcher监听器失败.", e);
        }
    }

    /**
     * 移除 子节点变更监听器
     *
     * @param path 监听节点
     */
    public void removePathChildrenWatcher(String path) throws ZookeeperException {
        try {
            watcherManager.removePathChildrenWatcher(path);
        } catch (Exception e) {
            throw new ZookeeperException("移除PathChildrenWatcher监听器失败.", e);
        }
    }
}
